package com.eking.services;

import java.util.Optional;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceGetsimplegroupsRequest;
import com.dingtalk.api.response.OapiAttendanceGetsimplegroupsResponse;
import com.eking.common.Constant;
import com.eking.tasks.ScheduleTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * 考勤组
 * Created by hexp on 2023/9/6 19:34
 */
@Component
@Slf4j
public class GroupsApi {

    @Autowired
    private ScheduleTask scheduleTask;
    /**
     * 批量获取考勤组信息
     */
    public OapiAttendanceGetsimplegroupsResponse getsimplegroups(){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getsimplegroups");
        OapiAttendanceGetsimplegroupsRequest req = new OapiAttendanceGetsimplegroupsRequest();
        req.setOffset(0L);
        req.setSize(100L);
        OapiAttendanceGetsimplegroupsResponse rsp = null;
        try {
            rsp = client.execute(req, scheduleTask.getToken());
        } catch (Exception e) {
            log.error("批量获取考勤组信息失败",e);
            throw new RuntimeException(e);
        }
        Assert.isTrue(rsp.isSuccess(),rsp.getMessage());
        return rsp;
    }

    /**
     * 根据考勤组名称获取考勤组groupId
     */
    public Optional<Long> getAttendanceGroup(){
        return Optional.ofNullable(getsimplegroups().getResult())
                .map(OapiAttendanceGetsimplegroupsResponse.AtGroupListForTopVo::getGroups)
                .get().stream().filter(t -> Constant.GROUP_NAME.equals(t.getGroupName()))
                .findFirst().map(OapiAttendanceGetsimplegroupsResponse.AtGroupForTopVo::getGroupId);
    }

}
